﻿using Mapster;
using Prism.Commands;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows.Input;


namespace SmartPlant.Modules.Base.ViewModels
{
    public class UserSetGroupViewModel : DialogViewModelBase, IDialogAware
    {
        private IntoolsUser _user;
        private List<IntoolsUser> _userList;
        private DelegateCommand<object> _okDialogCommand;
        private IOAuthService _authService;
        private ObservableCollection<UserGroupModel> _groupRights;
        public UserSetGroupViewModel(IDialogService dialogService, IOAuthService oAuthService) : base(dialogService)
        {
            Title = "编辑用户组";
            _authService = oAuthService;
            _groupRights = new ObservableCollection<UserGroupModel>();
        }

        public override async void OnDialogOpened(IDialogParameters parameters)
        {
            base.OnDialogOpened(parameters);

            _userList = parameters.GetValue<List<IntoolsUser>>("user");
            var groups = await _authService.GetAllUserGroupList();
            if (groups != null && groups.Count > 0)
            {
                foreach (var group in groups)
                {

                    var gModel = group.Adapt<UserGroupModel>();

                    //if (group.GroupId == _user.UserGroup.GroupId && !string.IsNullOrEmpty(_user.UserGroup.UserGroupName))
                    //{
                    //    gModel.IsCheck = true;
                    //}
                    _groupRights.Add(gModel);
                }
            }
        }

        public ObservableCollection<UserGroupModel> Groups
        {
            get
            {
                return _groupRights;
            }
            set { SetProperty(ref _groupRights, value); }
        }

        private ICommand _CheckBoxCommand;
        public ICommand CheckBoxCommand
        {
            get
            {
                if (_CheckBoxCommand != null)
                {
                    return _CheckBoxCommand;
                }
                _CheckBoxCommand = new DelegateCommand<object>(onCheckBoxCommand);
                return _CheckBoxCommand;
            }
        }
        /// <summary>
        /// 一个用户只能分配到一个用户组
        /// </summary>
        /// <param name="obj"></param>
        private void onCheckBoxCommand(object obj)
        {
            var cur = obj as UserGroupModel;
            if (cur.IsCheck)
            {
                //清楚其他的
                foreach (var otherGroup in Groups.Where(x => x.GroupId != cur.GroupId))
                {
                    otherGroup.IsCheck = false;
                }
            }
        }

        public ICommand OkDialogCommand
        {
            get
            {
                if (_okDialogCommand != null) return _okDialogCommand;
                _okDialogCommand = new DelegateCommand<object>(onOkDialogCommand);
                return _okDialogCommand;
            }
        }

        private async void onOkDialogCommand(object parameter)
        {
            if (Groups.IsEmpty())
            {
                Dialog.ShowAltert("系统中未存在可设置的用户组。");
                return;
            }
            try
            {
                bool? r = true;
                int CheckCount = 0;
                string groupId = null;
                foreach (var group in Groups)
                {
                    
                    if (group.IsCheck)
                    {
                        CheckCount += 1;
                        groupId = group.GroupId.ToString();
                    }
                    
                    //else
                    //    r = await _authService.UnAssignFromGroup(_user.UserId.ToString(), group.GroupId.ToString());
                }
                if (CheckCount==0)
                {
                    Dialog.ShowAltert("请勾选要分配的组！！！");
                    return;
                }
                if(CheckCount>1)
                {
                    Dialog.ShowAltert("User只能分配到一个Group，不能勾选多个Group！！！");
                    return;
                }
                foreach (var user in _userList)
                {
                    r = await _authService.AssignToGroup(user.UserId.ToString(), groupId);//服务器端添加user到group时会自动删除之前的group信息
                    if (r.HasValue && r.Value)
                    {
                        r = true;
                        continue;
                    }
                    else
                    {
                        r = false;
                        break;
                    }
                }
                if ((bool) r)
                {
                    Dialog.ShowAltert("编辑用户权限信息成功！！！");
                    RaiseRequestClose(new DialogResult(ButtonResult.OK));
                    return;
                }
                RaiseRequestClose(new DialogResult(ButtonResult.None));
            }
            catch (Exception x)
            {
                var xMessage = $"编辑用户权限信息失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }
    }
}
